package com.itheima.filter;

import cn.hutool.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决全站乱码问题，处理所有的请求
 */
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse rep, FilterChain filterChain) throws IOException, ServletException {
        //将父接口转为子接口
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) rep;

        //不需要过滤的url
        String path = request.getServletPath();
        String[] urls = {".html", ".js", ".css", ".ico", ".jpg", ".png"};
        boolean flag = true;
        for (String str : urls) {
            if (path.indexOf(str) != -1) {
                flag = false;
                break;
            }
        }

        //需要过滤的资源走这个逻辑
        if (flag) {
            //解决post请求中文数据乱码问题
            if (request.getMethod().equalsIgnoreCase("post")) {
                request.setCharacterEncoding("utf-8");
            }

            //解决跨域问题
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpStatus.HTTP_OK);
                return;
            }


            //处理响应乱码
            response.setContentType("application/json;charset=utf-8");
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
